﻿using System.Collections.Generic;
using System.Linq;
using DogshowRepository;

namespace Dogshow.Linq2SQLRepository
{
    public class TituleRepository : RepositoryBase, ITituleRepository
    {
        public int Sacuvaj(Model.Titula titula)
        {
            using (var model = new DogshowModel())
            {
                if (titula.Id > 0)
                {
                    var t = model.Titulas.SingleOrDefault(x => x.Id == titula.Id);
                    ModelMapper.Map(titula, t);
                    model.SubmitChanges();
                }
                else
                {
                    var t = ModelMapper.Map(titula);
                    model.Titulas.InsertOnSubmit(t);
                    model.SubmitChanges();
                    ModelMapper.Map(t, titula);
                }
                return titula.Id; 
            }
        }

        public IEnumerable<Model.Titula> VratiSve()
        {
            using (var model = new DogshowModel())
            {
                return model.Titulas.Select(x => ModelMapper.Map(x)).ToArray(); 
            }
        }

        public Model.Titula VratiPoId(int id)
        {
            using (var model = new DogshowModel())
            {
                var titula = model.Titulas.SingleOrDefault(x => x.Id == id);
                if (titula == null) return null;
                return ModelMapper.Map(titula); 
            }
        }
    }
}